/* eslint-disable no-console */
// 全局请求封装
import loginMethods from './login'

const http = {
  request: async function(params) {
    // 请求参数处理
    if (Object.prototype.toString.call(params.data) === '[object Array]') {
      params.data = JSON.stringify(params.data)
    } else if (Object.prototype.toString.call(params.data) === '[object Number]') {
      params.data = params.data + ''
    }

    // 发起请求
    return new Promise((resolve, reject) => {
      uni.request({
        dataType: 'json',
        responseType: params.responseType === undefined ? 'text' : params.responseType,
        header: {
          Authorization: uni.getStorageSync('Token')
        },
        url: (params.domain ? params.domain : import.meta.env.VITE_APP_BASE_API) + params.url,
        data: params.data,
        method: params.method === undefined ? 'POST' : params.method,
        success: (res) => {
          const responseData = res.data
          console.log("返回值");
          console.log(res);
          //当前时间戳
          const currentTimeStamp = new Date().getTime()
          const expiresTimeStamp = uni.getStorageSync('expiresTimeStamp')

          // 请求小程序码
          if (params.responseType === 'arraybuffer' && res.statusCode === 200) {
            return resolve(responseData)
          }

          // 1 请求成功
          if (responseData.code === 1) {
            resolve(responseData)
            console.log("par");
            console.log(params);
          }
          // 2 发生错误
          if (responseData.code === 2) {
            uni.showToast({
              title: res.msg,
              icon: error
            })
          }
          // 4 未授权
          if (res.statusCode == 401) {
            console.log(params);
            if (params.url.includes('/login') || params.url.endsWith('/login')) {
              uni.showToast({
                title: '账户状态异常，请联系管理员！',
                icon: 'error'
              });
            } else {
              let refreshToken = ''
              let Token = ''
              refreshToken = uni.getStorageSync("refreshToken")
              let isRefreshingToken = uni.getStorageSync("isRefreshingToken")
              console.log(refreshToken);
              console.log(refreshToken != '');
              console.log(isRefreshingToken);
              console.log(isRefreshingToken == false);
              if (refreshToken != null && isRefreshingToken == false) {
                let res = againRequest(params)
                console.log("res");
                resolve(res)

              } else {
                // 重设登录后跳转地址
                loginMethods.setRouteUrlAfterLogin()
                uni.removeStorageSync('expiresTimeStamp')
                uni.removeStorageSync('Token')
                uni.removeStorageSync('refreshToken')
                if (!params.dontTrunLogin) {
                  uni.showModal({
                    title: '提示',
                    content: uni.getStorageSync('hadLogin') ? '登录已过期，请重新登陆！' : '请先进行登录！',
                    cancelText: '取消',
                    confirmText: '确定',
                    success: res => {
                      if (res.confirm) {
                        uni.navigateTo({
                          url: '/pages/accountLogin/accountLogin'
                        })
                      }
                    }
                  })
                }
                resolve(responseData)
              }
            }
          }

          // 其他异常码
          if (responseData.code === 2) {
            if (!params.hasCatch) {
              uni.showToast({
                title: responseData.msg || responseData.data || 'Error',
                icon: 'none'
              })
            }
          }

          if (responseData.code !== '00000') {
            reject(responseData)
          }
        },
        fail: (err) => {
          console.log("请求失败");
          console.log(err);
          // 4 未授权,支付宝把401当成请求失败，在这里进行拦截
          if (err.statusCode == 401) {
            console.log(params);
            if (params.url.includes('/login') || params.url.endsWith('/login')) {
              uni.showToast({
                title: '账户状态异常，请联系管理员！',
                icon: 'error'
              });
            } else {
              let refreshToken = ''
              let Token = ''
              refreshToken = uni.getStorageSync("refreshToken")
              let isRefreshingToken = uni.getStorageSync("isRefreshingToken")
              console.log(refreshToken);
              console.log(refreshToken != '');
              console.log(isRefreshingToken);
              console.log(isRefreshingToken == false);
              if (refreshToken != null && isRefreshingToken == false) {
                let res = againRequest(params)
                console.log("res");
                resolve(err)

              } else {
                // 重设登录后跳转地址
                loginMethods.setRouteUrlAfterLogin()
                uni.removeStorageSync('expiresTimeStamp')
                uni.removeStorageSync('Token')
                uni.removeStorageSync('refreshToken')
                if (!params.dontTrunLogin) {
                  uni.showModal({
                    title: '提示',
                    content: uni.getStorageSync('hadLogin') ? '登录已过期，请重新登陆！' : '请先进行登录！',
                    cancelText: '取消',
                    confirmText: '确定',
                    success: res => {
                      if (res.confirm) {
                        uni.navigateTo({
                          url: '/pages/accountLogin/accountLogin'
                        })
                      }
                    }
                  })
                }
                resolve(responseData)
              }
            }
          }
          uni.showToast({
            title: '请求失败'
          })
          reject(err)
        }
      })
    })
  },
  getCartCount: () => {
    if (!uni.getStorageSync('Token')) {
      util.removeTabBadge()
      return
    }
    http.request({
        url: '/p/shopCart/prodCount',
        method: 'GET',
        dontTrunLogin: true,
        data: {}
      })
      .then(({
        data
      }) => {
        if (data > 0) {
          uni.setTabBarBadge({
            index: 2,
            text: data + ''
          })
          getApp().globalData.totalCartCount = data
        } else {
          uni.removeTabBarBadge({
            index: 2
          })
          getApp().globalData.totalCartCount = 0
        }
      })
  },
  onRequestFail: (params, responseData) => {
    console.error('============== 请求异常 ==============')
    console.log('接口地址: ', params.url)
    console.log('异常信息: ', responseData)
    console.error('============== 请求异常 end ==========')
  },
  /**
   * 登录成功后执行
   * @param {Object} result  登录成功返回的数据
   * @param {Object} fn 登录成功后的回调
   */
  loginSuccess: (result, fn) => {
    console.log("登录返回数据");
    console.log(result);
    // 保存登陆信息
    uni.setStorageSync('loginUser', result.user)
    // 保存成功登录标识,token过期判断
    uni.setStorageSync('hadLogin', true)
    const expiresTimeStamp = 1400000 + new Date().getTime()
    console.log();
    // 缓存token的过期时间
    uni.setStorageSync('expiresTimeStamp', expiresTimeStamp)
    // 把token存入缓存，请求接口数据时要用
    uni.setStorageSync('Token', result.accessToken)
    uni.setStorageSync("refreshToken", result.refreshToken)
    uni.setStorageSync('isRefreshingToken', false)
    if (fn) {
      fn()
    }
  }
}
const getRefreshToken = async () => {
  let refreshToken = uni.getStorageSync("refreshToken");
  console.log("401刷新token");
  uni.setStorageSync('isRefreshingToken', true);
  const res = await http.request({
    url: '/refresh',
    method: 'GET',
    data: {
      refreshToken: refreshToken
    },
    login: true,
    isRefreshing: true,
    dontTrunLogin: true
  });
  if (res.code == 1) {
    uni.setStorageSync('isRefreshingToken', false);
    uni.setStorageSync('expiresTimeStamp', 1200000 + new Date().getTime());
    // 把token存入缓存，请求接口数据时要用
    uni.setStorageSync('Token', res.map.accessToken);
    uni.setStorageSync("refreshToken", res.map.refreshToken);
    return res.map.accessToken;
  } else {
    uni.setStorageSync('isRefreshingToken', false);
  }
};
const againRequest = async (params) => {
  console.log("重新请求");
  let Token = await getRefreshToken(); // 确保getRefreshToken返回Promise并使用await等待结果
  console.log("刷新后tokan");
  console.log(Token);
  // 重新发送请求
  return http.request({
    header: {
      Authorization: Token
    },
    ...params
  });
};
export default http
